package com.ccys.db.handler;

import com.ccys.common.vo.ResponseResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static org.apache.commons.lang3.StringUtils.isNotBlank;

/**
 * 异常处理
 */
@RestControllerAdvice
public class SysExceptionHandler {


	@ExceptionHandler(Exception.class)
	public ResponseResult exceptionHandle(HttpServletRequest request, HttpServletResponse response, Exception e){
		String msg = "";
		String exceptionStr = e.toString();
		if(!exceptionStr.contains("HttpMediaTypeNotAcceptableException")){
			e.printStackTrace();
		}

		if(exceptionStr.contains("HttpRequestMethodNotSupportedException")){
			System.out.println("======请求方式错误======");
			msg = "请求方式错误，请用正确的方式请求";
		}else if(exceptionStr.contains("JsonMappingException")){
			System.out.println("======json映射转换异常======");
			msg = "json映射转换异常";
		}else if(exceptionStr.contains("IllegalArgumentException")){
			System.out.println("======非法参数，异常======");
			msg = "非法参数，异常";
		}else if(exceptionStr.contains("NumberFormatException")){
			System.out.println("======数字转换，异常======");
			msg = "数字转换，异常";
		}else if(exceptionStr.contains("BindException")){
			System.out.println("======参数绑定，异常======");
			msg = "参数绑定，异常";
		}else if(exceptionStr.contains("NullPointerException")){
			System.out.println("======  空数据，错误======");
			msg = "查不到相关记录，错误";
		}else if(exceptionStr.contains("HttpMediaTypeNotAcceptableException")){
			System.out.println("======地址找不到"+request.getRequestURL()+"======");
			msg = "地址找不到，错误";
		}else if(exceptionStr.contains("DuplicateKeyException")){
			System.out.println("======主键重复======");
			msg = "已存在,请勿重复添加";
		}else if(exceptionStr.contains("DataIntegrityViolationException")){
			System.out.println("======所提交的信息找不到资源，请刷新后重试======");
			msg = "所提交的信息找不到资源，请刷新后重试";
		}else {
			System.out.println("============系统发生未知异常啦！===============");
			msg = "系统开小差去了...";
		}

		return ResponseResult.error(500,msg);
	}


    private String getRemoteAddr(HttpServletRequest request) {
        String remoteAddr = request.getHeader("X-Real-IP");
        if (StringUtils.isNotBlank(remoteAddr)) {
            remoteAddr = request.getHeader("X-Forwarded-For");
        } else if (isNotBlank(remoteAddr)) {
            remoteAddr = request.getHeader("Proxy-Client-IP");
        } else if (isNotBlank(remoteAddr)) {
            remoteAddr = request.getHeader("WL-Proxy-Client-IP");
        }
        return remoteAddr != null ? remoteAddr : request.getRemoteAddr();
    }
}
